package com.info.zhiduoduo.admin.service;

import com.baomidou.mybatisplus.mapper.Condition;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.info.zhiduoduo.admin.model.vo.tempreport.UniqueStudioTotalProjectAmountVO;
import com.info.zhiduoduo.common.constants.project.CalcAmountType;
import com.info.zhiduoduo.common.utils.EasyExcelUtil;
import com.info.zhiduoduo.core.service.CoreProjectService;
import com.info.zhiduoduo.repository.dto.maker.StudioDetailDto;
import com.info.zhiduoduo.repository.entity.maker.MakerAccount;
import com.info.zhiduoduo.repository.entity.maker.MakerStudio;
import com.info.zhiduoduo.repository.mapper.maker.MakerAccountMapper;
import com.info.zhiduoduo.repository.mapper.maker.MakerStudioMapper;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.temporal.ChronoField;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class TempReportService {

	@Autowired
	CoreProjectService coreProjectService;

	@Resource
	MakerStudioMapper makerStudioMapper;
	@Resource
	MakerAccountMapper makerAccountMapper;

	public void exportUniqueStudioTotalProjectAmount(HttpServletResponse response) {

		List<UniqueStudioTotalProjectAmountVO> voList = Lists.newArrayList();

		Set<Integer> handledMakerSet = Sets.newHashSet();
		Map<Integer, StudioDetailDto> offAccounts = Maps.newHashMap();
		List<MakerStudio> makerStudios = new MakerStudio().selectList(Condition.create().eq("state", 2));
		for (MakerStudio makerStudio : makerStudios) {
			Integer userid = makerStudio.getUserid();
			if (handledMakerSet.contains(userid)) continue;
			StudioDetailDto studioDetail = makerStudioMapper.getStudioDetail(userid);
			if (studioDetail == null) continue;
			String idno = studioDetail.getIdno();
			if (idno.toLowerCase().contains("off")) {
				// 将off的创客添加进单独列表，此创客是有多个账号的, 先不处理
				offAccounts.put(userid, studioDetail);
				continue;
			}
			// 记录已操作
			handledMakerSet.add(userid);

			Date createTime = studioDetail.getCreatetime();
			String realname = studioDetail.getRealname();
			String username = makerStudio.getUsername();
			BigDecimal amount = getTotalAmountFrom(userid, 2020, 11);

			List<MakerAccount> sameList = new MakerAccount().selectList(Condition.create().like("idno", studioDetail.getIdno()));
			if (CollectionUtils.isNotEmpty(sameList)) {
				// 这些应该都是off里面的
				for (MakerAccount makerAccount : sameList) {
					Integer sameUserid = makerAccount.getUserid();
					if (handledMakerSet.contains(sameUserid)) continue;
					if (!makerAccount.getIdno().toLowerCase().contains("off")) {
						// 不包含off， 特殊打印日志, 放过，当作是单独一个创客
						log.info("身份证类似，但不包含off，又是没有处理过的，放过：userid={}, realname={}, idno={}, 主studio userid={}，realname={}, idno={}",
								sameUserid, makerAccount.getRealname(), makerAccount.getIdno(), userid, realname, idno);
						continue;
					}

					handledMakerSet.add(sameUserid);
					offAccounts.remove(sameUserid);

					MakerStudio sameStudio = new MakerStudio().selectById(sameUserid);
					if (sameStudio != null) {
						realname += ("," + makerAccount.getRealname());
						username += ("," + sameStudio.getUsername());
					}
					amount = amount.add(getTotalAmountFrom(sameUserid, 2020, 11));

				}
			}

			// 在平台交易额达到100到500万之间
			double v = amount.doubleValue();
			if (v >= 1000000) {
				voList.add(new UniqueStudioTotalProjectAmountVO().setIdno(idno)
						.setCreateTime(createTime)
						.setRealname(realname)
						.setUsername(username)
						.setAmount(amount)
						.setBindCompname(studioDetail.getBindcompname()));
			}

		}

		if (MapUtils.isNotEmpty(offAccounts)) {
			log.info("还有off的创客没有处理掉！！！！！！size={}", offAccounts.size());
			for (Map.Entry<Integer, StudioDetailDto> entry : offAccounts.entrySet()) {
				Integer userid = entry.getKey();
				StudioDetailDto studioDetail = entry.getValue();

				MakerStudio makerStudio = new MakerStudio().selectById(userid);

				String idno = studioDetail.getIdno();
				Date createTime = studioDetail.getCreatetime();
				String realname = studioDetail.getRealname();
				String username = makerStudio.getUsername();
				BigDecimal amount = getTotalAmountFrom(userid, 2020, 11);

				// 在平台交易额达到100到500万之间
				double v = amount.doubleValue();
				if (v >= 1000000) {
					voList.add(new UniqueStudioTotalProjectAmountVO().setIdno(idno)
							.setCreateTime(createTime)
							.setRealname(realname)
							.setUsername(username)
							.setAmount(amount)
							.setBindCompname(studioDetail.getBindcompname()));
				}
			}
		}

		EasyExcelUtil.download(response, "创客统计总金额", UniqueStudioTotalProjectAmountVO.class, voList);
	}

	private BigDecimal getTotalAmountFrom(int userid, int year, int month) {
		LocalDate from = LocalDate.of(year, month, 1);
		LocalDate to = LocalDate.now().with(ChronoField.DAY_OF_MONTH, 1);

		BigDecimal totalAmount = BigDecimal.ZERO;
		LocalDate curr = from;
		while (curr.isAfter(to)) {
			totalAmount = totalAmount.add(
					coreProjectService.getUserMonthlyTotalAmountByYearMonth(userid, CalcAmountType.PROCESSING, curr.getYear(),
							curr.getMonthValue()));
			curr = curr.plusMonths(1);
		}
		return totalAmount;
	}
}
